import { SongDetailProp, StateProp } from '@/store/type'
import { computed, ComputedRef } from 'vue'
import { useStore } from 'vuex'
import { add, remove } from '@/assets/js/array-store'
import { FAVORITE_KEY } from '@/assets/js/constant'
const MAX_LEN = 100

export default (song: ComputedRef<SongDetailProp>) => {
    const store = useStore<StateProp>()
    const favoriteList = computed<SongDetailProp[]>(() => store.state.favoriteList)

    const favoriteIcon = computed<{ [props: string]: boolean }>(() => {
        const flag = includeItem(favoriteList.value, song.value)
        return {
            'icon-not-favorite': !flag,
            'icon-favorite': flag
        }
    })
    const toggleFavorite = () => {
        const list = favoriteList.value
        let newList
        if (includeItem(list, song.value)) {
            // remove
            newList = remove(FAVORITE_KEY, compare)
            console.log('remove')
        } else {
            // add
            newList = add(song.value, FAVORITE_KEY, compare, MAX_LEN)
            console.log('add')
        }
        store.commit('setFavoriteList', newList)
    }

    function compare (item: any) {
        return item.id === song.value.id
    }
    function includeItem (arr: any[], obj: any) {
        return arr.some(item => item.id === obj.id)
    }
    return {
        favoriteIcon,
        toggleFavorite
    }
}
